package com.zxp.mall.authserve.controller;

import com.alibaba.fastjson.TypeReference;
import com.zxp.mall.authserve.feign.MemberFeignService;
import com.zxp.mall.authserve.feign.ThirdPartyFeignService;
import com.zxp.mall.authserve.vo.UserLoginVo;
import com.zxp.mall.authserve.vo.UserRegisterVo;
import com.zxp.mall.common.constant.AuthServerConstant;
import com.zxp.mall.common.enums.BizCodeEnum;
import com.zxp.mall.common.utils.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Controller
public class LoginController {

    @Autowired
    private ThirdPartyFeignService thirdPartyFeignService;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    @GetMapping("/sms/sendcode")
    @ResponseBody
    public R sendCode(@RequestParam String phone) {
        String key = AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone;
        String s = redisTemplate.opsForValue().get(key);
        if (!StringUtils.isEmpty(s)) {
            long l = Long.parseLong(s.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000) {
                return R.error(BizCodeEnum.VALID_SMS_CODE_EXCEPTION.getCode(),
                        BizCodeEnum.VALID_SMS_CODE_EXCEPTION.getMsg());
            }
        }

//        String code = UUID.randomUUID().toString().substring(0, 5);
        Random random = new Random();
        String code = String.valueOf(random.nextInt(9000) + 1000);
        System.out.println("发送的验证码是--->" + code);
        // 缓存校验码
        redisTemplate.opsForValue().set(AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone, code + "_" + System.currentTimeMillis(), 5,
                TimeUnit.MINUTES);
//        thirdPartyFeignService.sendCode(phone, code);
        return R.ok();
    }


    //    attributes 重定向携带数据 其实就是使用session原理 ， 只要跳到下一个页面取出这个数据 session就会把数据给删除掉 todo：session 分布式的问题
    @PostMapping("/registe")
    public String register(@Valid UserRegisterVo vo, BindingResult result, RedirectAttributes attributes) {
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream()
                    .collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/register.html";
        }

//        校验验证码
        String code = vo.getCode();
        String phone = vo.getPhone();
        String redisKey = AuthServerConstant.SMS_CODE_CACHE_PREFIX + phone;
        String s = redisTemplate.opsForValue().get(redisKey);
        if (!StringUtils.isEmpty(s)) {
            if (s.split("_")[0].equalsIgnoreCase(code)) {
                redisTemplate.delete(redisKey);
                R r = memberFeignService.register(vo);
                if (r.getCode() == 0) {
//                    注册成功
                    return "redirect:http://auth.gulimall.com/login.html";
                } else {
//                    注册失败
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", r.getData("msg", new TypeReference<String>() {
                    }));
                    attributes.addFlashAttribute("errors", errors);
                    return "redirect:http://auth.gulimall.com/register.html";
                }
            } else {
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                attributes.addFlashAttribute("errors", errors);
                return "redirect:http://auth.gulimall.com/register.html";
            }
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/register.html";
        }
    }

    @GetMapping("/login.html")
    public String loginPage(HttpSession session) {
        Object attribute = session.getAttribute(AuthServerConstant.LOGIN_USER);
        if (attribute == null) {
            return "login";
        } else {
            return "redirect:http://gulimall.com";
        }
    }


    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes attributes) {
        R r = memberFeignService.login(vo);
        if (r.getCode() == 0) {
            return "redirect:http://gulimall.com";
        } else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", r.getData("msg", new TypeReference<String>() {
            }));
            attributes.addFlashAttribute("errors", errors);
            return "redirect:http://auth.gulimall.com/login.html";
        }
    }
}
